from typing import List
from ultralytics import YOLO
from app.schema.detection import DetectionResult


async def predict_image(model: YOLO, image) -> List[DetectionResult]:
    try:
        # 调整图像大小（可选）
        # image = cv2.resize(image, (640, 640))

        # 执行推理
        results = model(image, verbose=False)

        # 解析结果
        detections = []
        for result in results:
            for box in result.boxes:
                detections.append(DetectionResult(
                    class_id=int(box.cls),
                    class_name=result.names[int(box.cls)],
                    confidence=float(box.conf),
                    xmin=int(box.xyxy[0][0]),
                    ymin=int(box.xyxy[0][1]),
                    xmax=int(box.xyxy[0][2]),
                    ymax=int(box.xyxy[0][3])
                ))
        return detections
    except Exception as e:
        raise RuntimeError(f"Detection failed: {str(e)}")